//
//  AddCarViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/9/2.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "AddCarViewController.h"

#import "AddCarManaView.h"
#import "CarDetCell.h"
#import "MapSelPlaceViewController.h"
#import "HouseImagesViewController.h"
@interface AddCarViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MapSelPlaceViewControllerDelegate,HouseImagesViewControllerDelegate>{
    NSMutableArray *array;
    UITableViewCellEditingStyle editStyle;//
    AddCarManaView *views;
    
    UIImagePickerController *imagepc;
    UIView *view1;
    UIView *view2;
    
    CarDetCell *cell;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *arr1;

@property (nonatomic,copy)NSString *imgUrl;//图片路径
@property (nonatomic,strong)NSMutableArray *arrHeadImgs;
@property (nonatomic,strong)NSMutableArray *arrImgs;//详情图片
@property (nonatomic,copy)NSString *strid;//车辆性质
@property (nonatomic,copy)NSString *lat;
@property (nonatomic,copy)NSString *lng;
@property (nonatomic,copy)NSString *province;
@property (nonatomic,copy)NSString *city;
@property (nonatomic,copy)NSString *area;

@end

@implementation AddCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    array = [NSMutableArray array];
    _arr1 = [NSMutableArray array];
    _arrHeadImgs = [NSMutableArray array];
    _arrImgs = [NSMutableArray array];
    
    [array addObject:@"sss"];
    [self showNav:@"添加商品"];
    [self loadUI];
    
    [self loadData];
}

- (void)loadUI{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, ScreenHeight-50, ScreenWidth, 50);
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickTJ) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    views = [[[NSBundle mainBundle] loadNibNamed:@"AddCarManaView" owner:nil options:nil] lastObject];
    views.frame = CGRectMake(0, 0, ScreenWidth, 840);
    _tableView.tableHeaderView = views;
    
    //新车标签
    views.lab1.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click1)];
    [views.lab1 addGestureRecognizer:tap1];
    //选择日期
    views.lab3.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click3)];
    [views.lab3 addGestureRecognizer:tap3];
    //地图
    views.lab4.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click4)];
    [views.lab4 addGestureRecognizer:tap4];
    //图片
    views.views.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImages)];
    [views.views addGestureRecognizer:tap];
    
}

- (void)clickImages{
    HouseImagesViewController *images = [[HouseImagesViewController alloc] init];
    images.delegate = self;
    [self.navigationController pushViewController:images animated:YES];
}
#pragma -mark HouseImagesViewControllerDelegate
-(void)sendImgUrl:(NSMutableArray *)imgUrl{
    _arrHeadImgs = imgUrl;
    NSMutableArray *arrImg = [NSMutableArray array];
    for (NSString *aaa in imgUrl) {
        NSString *str = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],aaa];
        [arrImg addObject:str];
    }
    
    UIView *v = [WTImageScroll ShowNetWorkImageScrollWithFream:CGRectMake(0, 0, ScreenWidth, 200) andImageArray:arrImg andBtnClick:^(NSInteger tagValue) {
        [self clickImages];
    }];
    [views.views addSubview:v];
}

- (void)click1{
    view1 = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-250, ScreenWidth, 250)];
    view1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view1];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(10, 0, 40, 40);
    [btn1 setTitle:@"取消" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:btn1];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(ScreenWidth-50, 0, 40, 40);
    [btn2 setTitle:@"确定" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:btn2];
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, 210)];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [view1 addSubview:pickerView];
}

- (void)clickCancel{
    [view1 removeFromSuperview];
    [view2 removeFromSuperview];
}

- (void)clickSure{
    [view1 removeFromSuperview];
    [view2 removeFromSuperview];
}
//
- (void)click3{
    view2 = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-250, ScreenWidth, 250)];
    view2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view2];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(10, 0, 40, 40);
    [btn1 setTitle:@"取消" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    [view2 addSubview:btn1];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(ScreenWidth-50, 0, 40, 40);
    [btn2 setTitle:@"确定" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    [view2 addSubview:btn2];
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, 210)];
    datePicker.backgroundColor = [UIColor grayColor];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"];
    datePicker.date = [NSDate date];
    [view2 addSubview:datePicker];
    //添加事件
    [datePicker addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventValueChanged];
}

- (void)selectDate:(id)sender{
    UIDatePicker *picker = (UIDatePicker *)sender;
    NSDate *date = picker.date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [df stringFromDate:date];
    views.lab3.text = str;
    NSLog(@"str:%@",str);
    
}
//选择地址
- (void)click4{
    MapSelPlaceViewController *place = [[MapSelPlaceViewController alloc] init];
    place.delegate = self;
    [self.navigationController pushViewController:place animated:YES];
}
#pragma -mark MapSelPlaceViewControllerDelegate
-(void)sendLat:(NSString *)lat sendLng:(NSString *)lng{
    _lat = lat;
    _lng = lng;
}

-(void)sendText:(NSString *)text Province:(NSString *)proce City:(NSString *)city Area:(NSString *)area{
    views.lab4.text = [NSString stringWithFormat:@"%@,%@,%@",proce,city,area];
    views.text7.text = text;
    _province = proce;
    _city = city;
    _area = area;
}
#pragma -mark UIPickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _arr1.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *str = [_arr1[row] objectForKey:@"name"];
    return str;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *str = [_arr1[row] objectForKey:@"name"];
    views.lab1.text = str;
    views.lab2.text = views.lab1.text;
    _strid = [_arr1[row] objectForKey:@"id"];
    NSLog(@"str:%@",str);
}

#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CarDetCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.text.backgroundColor = [UIColor lightGrayColor];
    cell.text.delegate = self;
    cell.text.text = @"请填写";
    cell.text.textColor = [UIColor grayColor];
    
    cell.images.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Alert:)];
    UIView *v = [tap view];
    v.tag = indexPath.row;
    [cell.images addGestureRecognizer:tap];
    
    return cell;
}

- (void)Alert:(id)sender{
    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
    UIView *v = [tap view];
    NSInteger tag = v.tag;
    if (tag == 0) {
        NSLog(@"000");
    }else if (tag == 1){
        NSLog(@"111");
    }else if (tag == 2){
        NSLog(@"222");
    }else{
        NSLog(@"333");
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}
//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
}

#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    cell.images.image = img;
    cell.imgPC.hidden = YES;
    cell.labSC.hidden = YES;
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//图片上传
- (void)loadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSString *error = [NSString stringWithFormat:@"%li",[[op objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            //_imgUrl = [op objectForKey:@"result"];
            NSString *str = [op objectForKey:@"result"];
            [_arrImgs addObject:str];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 350.0;
}
//
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//提供编辑的样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return editStyle;
}

//提交编辑状态
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleInsert) {
        
        [array insertObject:@"aaa" atIndex:indexPath.row];
        [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }else if (editingStyle == UITableViewCellEditingStyleDelete){
        [array removeObjectAtIndex:indexPath.row];
        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40.0)];
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(16, 10, ScreenWidth-32, 30);
    [btn setTitle:@"+  添加更多图文说明" forState:UIControlStateNormal];
    [btn setTitleColor:COLOR_RGB(17, 100, 253, 1) forState:UIControlStateNormal];
    btn.layer.cornerRadius = 5.0;
    btn.layer.borderWidth = 1.0;
    btn.layer.borderColor = COLOR_RGB(17, 100, 253, 1).CGColor;
    [btn addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.0;
}

- (void)clickAdd{
    if (array.count>=4) {
        [self showAlert:@"最多添加4组图文说明"];
        return;
    }
    editStyle = UITableViewCellEditingStyleInsert;
    if (_tableView.isEditing) {
        [_tableView setEditing:NO animated:YES];
    }else{
        [_tableView setEditing:YES animated:YES];
    }
}

#pragma mark - UITextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请填写"]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = @"请填写";
        textView.textColor = [UIColor grayColor];
    }
}
//购车-汽车性质
- (void)loadData{
    NSString *url = [NSString stringWithFormat:@"%@/App/CarBuying/type",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"购车res:%@",responseObject);
        _arr1 = [responseObject objectForKey:@"result"];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
//购车-产品上传
- (void)clickTJ{
    if (_arrHeadImgs.count == 0) {
        [self showAlert:@"请上传图片"];
        return;
    }else if (views.text1.left == 0){
        [self showAlert:@"请输入商品名称"];
        return;
    }else if (views.lab1.text == 0){
        [self showAlert:@"请选择标签"];
        return;
    }else if (views.text2.text == 0){
        [self showAlert:@"请输入指导价"];
        return;
    }else if (views.text3.text == 0){
        [self showAlert:@"请输入销售价"];
        return;
    }else if (views.text4.text == 0){
        [self showAlert:@"请输入车漆颜色"];
        return;
    }else if (views.text5.text == 0){
        [self showAlert:@"请输入车辆售后"];
        return;
    }else if (views.text6.text == 0){
        [self showAlert:@"请输入行驶公里"];
        return;
    }else if (views.lab3.text == 0){
        [self showAlert:@"请选择出厂日期"];
        return;
    }else if (views.lab4.text == 0){
        [self showAlert:@"请选择地址"];
        return;
    }else if (views.text7.text == 0){
        [self showAlert:@"请输入具体地址"];
        return;
    }
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    _imgUrl = [_arrImgs componentsJoinedByString:@"|"];
    NSString *strhead = [_arrHeadImgs componentsJoinedByString:@"|"];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:strhead forKey:@"photo"];
    [parmas setObject:views.text1.text forKey:@"brand"];
    [parmas setObject:views.lab1.text forKey:@"type"];
    [parmas setObject:views.text2.text forKey:@"guideprice"];
    [parmas setObject:views.text3.text forKey:@"sellingprice"];
    [parmas setObject:views.text4.text forKey:@"carcolor"];
    [parmas setObject:views.text5.text forKey:@"customerservice"];
    [parmas setObject:views.text6.text forKey:@"travel"];
    [parmas setObject:views.lab3.text forKey:@"thefactorytime"];
    [parmas setObject:_province forKey:@"province"];
    [parmas setObject:_city forKey:@"city"];
    [parmas setObject:_area forKey:@"area"];
    [parmas setObject:views.text7.text forKey:@"detailedaddress"];
    [parmas setObject:_imgUrl forKey:@"img"];
    [parmas setObject:@"" forKey:@"detailsa"];//车辆详情detailsa
    [parmas setObject:_lng forKey:@"longitude"];
    [parmas setObject:_lat forKey:@"latitude"];
    [parmas setObject:views.text7.text forKey:@"address"];
    [parmas setObject:_merid forKey:@"productid"];
    [parmas setObject:_strid forKey:@"type"];
    NSLog(@"parmas:%@",parmas);
    
    NSString *url = [NSString stringWithFormat:@"%@/App/CarBuying/upload",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"购车-产品上传res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
